﻿using AdminWeb.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using XW.Web.Framework;
using XW.Web.Framework.Jwt;
using Microsoft.Extensions.Options;
using XW.Core;
using XW.Data;
using Microsoft.IdentityModel.Tokens;
using XW.Utils;
using Microsoft.AspNetCore.Http.Extensions;
using AdminWeb.Areas.Sys.Models;
using SqlSugar;

namespace AdminWeb.Areas.Sys.Controllers
{
    /// <summary>
    /// 用户控制器
    /// </summary>

    [Area("Sys")]
    [Authorize]
    public class UserController   : BaseController
	{ 
        private readonly IOptions<JwtSecurityTokenOptions> _jwtOptions;
        private readonly ILogger<UserController> _logger;
        private readonly SqlSugarRepository<SysUser> _userRep;
        private readonly SqlSugarRepository<SysRole> _roleRep;
        private readonly SqlSugarRepository<SysUserRole> _userRoleRep;

        public UserController(ILogger<UserController> logger, IOptions<JwtSecurityTokenOptions> jwtOptions,
            SqlSugarRepository<SysUser> userRep, SqlSugarRepository<SysRole> roleRep, SqlSugarRepository<SysUserRole> userRoleRep)
        {
            _logger = logger;
            _jwtOptions = jwtOptions;
            _userRep = userRep;
            _roleRep = roleRep;
            _userRoleRep = userRoleRep;
        }
        /// <summary>
        /// 用户列表
        /// </summary>
        /// <returns></returns>
        public IActionResult List()
        {
            // string url = Request.GetEncodedPathAndQuery();
            return View();
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> PageAsync() {
            var pageModel = CommonHelper.GetPageModel4Form<UserPageModel>();
            RefAsync<int> count = 0;
            var query = _userRep.AsQueryable();
            pageModel.Keyword = pageModel.Keyword.SafeTrim();
			// 关键字查询
			query.WhereIF(pageModel.Keyword.IsNotNullAndEmpty(),
                u => u.Account.Contains(pageModel.Keyword)
                || u.NickName.Contains(pageModel.Keyword)
                || u.Phone.Contains(pageModel.Keyword)
                || u.Email.Contains(pageModel.Keyword)
                || u.RealName.Contains(pageModel.Keyword)
                || u.Remark.Contains(pageModel.Keyword));

            // 排序
            if (pageModel.SortField.IsNotNullAndEmpty())
            {
                query.OrderByPropertyName(pageModel.SortField, pageModel.SortType == "desc" ? OrderByType.Desc : OrderByType.Asc);
            }
            // 排序
            var list = await query.ToPageListAsync(pageModel.Page,pageModel.Limit, count);

            return GetSuccessResult(new   { items = list , count = count.Value });
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <returns></returns>
        public IActionResult Edit(int id=0) {
            SysUser user = null;
            if (id > 0) {
                user = _userRep.GetById(id);
                if (user == null)
                {
                    return Content("<h1>用户不存在！</h1>");
                }
                var roleIds = _userRoleRep.AsQueryable().Where(d => d.IsDelete == false).Where(d => d.UserId == id).Select(d => d.RoleId).ToList();
                user.Roles = roleIds;
            }
            else
            {
                user = new SysUser();
                user.Roles = new List<long>();
            }
            var roles = _roleRep.AsQueryable().Where(d => d.IsDelete == false).OrderBy(d => d.Name).ToList();
            ViewData["Roles"] = roles;
            
            return View(user); 
        }

        /// <summary>
		/// 修改当前用户的备注
		/// </summary>
		/// <returns></returns>
		[Authorize]
        public IActionResult Save()
        {
            string? Account = this.Request.Form["Account"];
            string? nickName = this.Request.Form["NickName"];
            string? RealName = this.Request.Form["RealName"];
            string? Remark = this.Request.Form["remark"];
            string? phone = this.Request.Form["phone"];
            string? email = this.Request.Form["email"];
            long id = CommonHelper.ToInt64( this.Request.Form["id"]);
            string Roles = CommonHelper.ToString( this.Request.Form["Roles"]);

            var db = _userRep.AsTenant();
            db.BeginTran();
            try
            {
                if (id == 0)
                {
                    string? Password = this.Request.Form["Password"];
                    if (Password.IsNullOrEmpty())
                    {
                        return GetErrorResult("密码不能为空！");
                    }
                    if (Account.IsNullOrEmpty())
                    {
                        return GetErrorResult("账号不能为空");
                    }
                    string salt = RandomHelper.GetRandStr();
                    var user = new SysUser();
                    user.Account = Account;
                    user.NickName = nickName;
                    user.RealName = RealName;
                    user.Remark = Remark;
                    user.Phone = phone;
                    user.Email = email;
                    user.Salt = salt;
                    user.Password = CryptoHelper.MD5(string.Format("{0}{1}", salt, Password));
                    _userRep.Insert(user);
                    id = user.Id; 
                }
                else
                {
                    _userRep.AsUpdateable()
                   .SetColumns(u => u.NickName == nickName)
                   .SetColumns(u => u.RealName == RealName)
                   .SetColumns(u => u.Remark == Remark)
                   .SetColumns(u => u.Phone == phone)
                   .SetColumns(u => u.Email == email)
                   .setColumnsUpdateUserAndTime()
                   .Where(u => u.Id == id).ExecuteCommand(); 
                }
                // 删除旧的
                var roles = Roles.Split(',').Select(d => d.ToLong()).ToList();
                _userRoleRep.AsDeleteable().Where(d=>d.UserId == id).ExecuteCommand();
                // 插入
                foreach (var roleId in roles)
                {
                    _userRoleRep.Insert(new SysUserRole { UserId = id, RoleId = roleId });
                }
                db.CommitTran(); // 提交事务 
                return GetSuccessResult("保存成功！");
            }
            catch (Exception ex)
            {

                db.RollbackTran(); // 提交事务
                return GetErrorResult(ex.Message);
            } 
    
        }
    }
}
